import Vue from 'vue'
import { set } from 'lodash'

/**
 * v-throttle
 * 节流,2s点击执行一次
 */
Vue.directive('throttle', {
  bind: (el, binding) => {
    let throttleTime = binding.value // 防抖时间
    if (!throttleTime) { // 用户若不设置节流时间，则默认2s
      throttleTime = 2000
    }
    let cbFun
    el.addEventListener('click', event => {
      if (!cbFun) { // 第一次执行
        cbFun = setTimeout(() => {
          cbFun = null
        }, throttleTime)
      } else {
        event && event.stopImmediatePropagation()
      }
    }, true)
  }
})

/**
 * v-drag
 * 弹窗拖拽功能
 */
Vue.directive('drag', {
  bind (el, binding, vnode) {
    const dialogHeaderEl = el.querySelector('.q-card__section')
    const dragDom = el.querySelector('.q-card__section').parentNode
    dialogHeaderEl.style.cssText += ';cursor:move;'
    dragDom.style.cssText += ';top:0px;'

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const getStyle = (function () {
      if (window.document.currentStyle) {
        return (dom, attr) => dom.currentStyle[attr]
      } else {
        return (dom, attr) => getComputedStyle(dom, false)[attr]
      }
    })()

    dialogHeaderEl.onmousedown = (e) => {
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft
      const disY = e.clientY - dialogHeaderEl.offsetTop

      const dragDomWidth = dragDom.offsetWidth
      const dragDomHeight = dragDom.offsetHeight

      const screenWidth = document.body.clientWidth
      const screenHeight = document.body.clientHeight

      const minDragDomLeft = dragDom.offsetLeft
      const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth

      const minDragDomTop = dragDom.offsetTop
      const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomHeight

      // 获取到的值带px 正则匹配替换
      let styL = getStyle(dragDom, 'left')
      let styT = getStyle(dragDom, 'top')

      if (styL.includes('%')) {
        // eslint-disable-next-line no-useless-escape
        styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100)
        // eslint-disable-next-line no-useless-escape
        styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100)
      } else {
        styL = +styL.replace(/\px/g, '')
        styT = +styT.replace(/\px/g, '')
      }

      document.onmousemove = function (e) {
        // 通过事件委托，计算移动的距离
        let left = e.clientX - disX
        let top = e.clientY - disY

        // 边界处理
        if (-(left) > minDragDomLeft) {
          left = -minDragDomLeft
        } else if (left > maxDragDomLeft) {
          left = maxDragDomLeft
        }

        if (-(top) > minDragDomTop) {
          top = -minDragDomTop
        } else if (top > maxDragDomTop) {
          top = maxDragDomTop
        }

        // 移动当前元素
        dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`

        // emit onDrag event
        vnode.child.$emit('dragDialog')
      }

      document.onmouseup = function (e) {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
})
/**
 * 增加鼠标移上效果
 * 用于搜索条件过短的情况
 */
Vue.directive('longth', {
  bind: (el, binding) => {
    const { isLongth, width } = binding.value
    if (isLongth) {
      el.style.width = '200px'
      el.addEventListener('focus', (e) => {
        el.style.width = width || '300px'
      }, true)
      el.addEventListener('blur', () => {
        el.style.width = '200px'
      }, true)
      el.style.transition = '1s'
    }
  }
})
// 点击图片放大
Vue.directive('enlarge', {
  inserted (el) {
    el.addEventListener('click', function (e) {
      e.stopPropagation()
      const imgSrc = el.getAttribute('src')
      let _showImg_ = document.getElementById('__showImg__')
      if (_showImg_) {
        _showImg_.style.display = 'flex'
        const childImg = _showImg_.childNodes[0]
        childImg.setAttribute('src', imgSrc)
      } else {
        _showImg_ = document.createElement('div')
        const body = document.body
        _showImg_.innerHTML = `<img src="${imgSrc}" style="width: 430px" />`
        _showImg_.setAttribute('id', '__showImg__')
        _showImg_.setAttribute(
          'style',
          'display: flex;justify-content: center;align-items:center;position:fixed;z-index:10000;left:0;top:0;right:0;bottom:0;background:rgba(0,0,0,0.7);'
        )
        body.appendChild(_showImg_)

        _showImg_.addEventListener('click', function (e) {
          e.stopPropagation()
          this.style.display = 'none'
        })
      }
    })
  }
})

// 非负数
Vue.directive('pureNum', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el, binding, vnode) {
    el.pureNum = function (e) {
      const val = e.target.value.replace(/[^\d]/g, '')

      e.target.value = val
      set(vnode.context, binding.expression, val)
    }
    if (!el.querySelector('input')) el.addEventListener('input', el.pureNum, false)
    else el.querySelector('input').addEventListener('input', el.pureNum, false)
  },
  unbind: function (el) {
    if (!el.querySelector('input')) el.removeEventListener('input', el.pureNum, false)
    else el.querySelector('input').removeEventListener('input', el.pureNum, false)
  }
})

const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}

// 正整数
Vue.directive('plusNum', {
  bind: function (el, binding) {
    const input = el.getElementsByTagName('input')[0]
    const num = binding.value || ''
    console.log(binding)
    input.onkeyup = function (e) {
      if (input.value.length === 1) {
        input.value = input.value.replace(/[^1-9]/g, num)
      } else {
        input.value = input.value.replace(/[^\d]/g, '')
      }
      trigger(input, 'input')
    }
    input.onblur = function (e) {
      if (input.value === '') {
        input.value = num
      }
      if (input.value.length === 1) {
        input.value = input.value.replace(/[^1-9]/g, num)
      } else {
        input.value = input.value.replace(/[^\d]/g, '')
      }
      trigger(input, 'input')
    }
  }
})
